package gw.com.android.utils;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.gwtsz.gts2.hx.R;

import java.util.List;

import gw.com.android.ui.views.ImageWatcher;
import www.com.library.util.DeviceUtil;

/**
 * 处理有批量图片需要显示的需求
 * 目前：圈子，我的帖子，分析师观点，分析师点评 - 就这些地方。
 */
public class ImageLayoutHelper {

    private static ImageWatcher watcher;

    private static volatile ImageLayoutHelper mInstance;//引用

    private int rightMargin = 5;// 多张图片时，图的右间距,单位dp

    private int default_W_or_h_of_singleImg = 180;//单位dp

    private int widthOfSingleImg;
    private int heightOfSingleImg;// 单张图情况下，宽高要从外界传入

    private boolean ifParseSizeCorrect = false;

    public void setSizeofSingleImg(Context context, String imgSize) {
        //解析形如 100*100
        try {
            ifParseSizeCorrect = true;
            String[] s = imgSize.split("\\*");
            this.widthOfSingleImg = Integer.parseInt(s[0]);
            this.heightOfSingleImg = Integer.parseInt(s[1]);
        } catch (NumberFormatException e) {
            Log.e("setSizeofSingleImgErr", "图片尺寸解析出错，现在使用默认尺寸进行替换");
            ifParseSizeCorrect = false;
            //如果出现解析出错的情况？怎么弄？
            this.widthOfSingleImg = dp2px(context, default_W_or_h_of_singleImg);
            this.heightOfSingleImg = dp2px(context, default_W_or_h_of_singleImg);
        }
    }

    /**
     * 获取单例引用
     */
    public static ImageLayoutHelper getInstance(ImageWatcher watcherT) {
        ImageLayoutHelper inst = mInstance;
        if (inst == null) {
            synchronized (ImageLayoutHelper.class) {
                inst = mInstance;
                if (inst == null) {
                    inst = new ImageLayoutHelper();
                    mInstance = inst;
                }
            }
        }
        watcher = watcherT;
        return inst;
    }

    private static int dp2px(Context mContext, float dp) {
        return (int) (dp * mContext.getResources().getDisplayMetrics().density + 0.5f);
    }

    /**
     * 晒单的显示效果
     */
    public void addImageIntoLayout(Context context, LinearLayout layout, String url, final List<ImageView> images, final List<String> urlList) {
        final ImageView iv = new ImageView(context);
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        int width = DeviceUtil.instance().getScreenPixelsWidth(context) / 3;
        int height = (int) (width * 1.0F / 301 * 410);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);

        images.add(iv);
        urlList.add(url);
        layout.addView(iv, layoutParams);

        if (url != null && url.length() > 0) {
            Glide.with(context).load(url).placeholder(R.mipmap.a_forum_nopic1).error(R.mipmap.a_forum_nopic1).into(iv);
        } else {
            iv.setVisibility(View.GONE);
        }

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                watcher.show(iv, images, urlList);
            }
        });
    }


    /**
     * 重载方法，增加末尾一个参数，是为了让多张图可以自适应宽
     *
     * @param currentIndex 如果是多张图，这个值则表示当前图的index;单张图，传0即可
     */
    public void addImageIntoLayout(Context context, int currentIndex, LinearLayout layout, String url, final List<ImageView> images, final List<String> urlList, boolean ifOnlyOne, int computeImageLayoutMaxWidth) {
        int eachWidth = (computeImageLayoutMaxWidth) / 3;
        deal(context, eachWidth, currentIndex, layout, url, images, urlList, ifOnlyOne);
    }

    /**
     * 将一张图，加到ImageLayout中
     * <p>
     * 多张图情况下，取定宽92dp
     *
     * @param currentIndex 如果是多张图，这个值则表示当前图的index
     * @param layout       目标layout
     * @param url          当前的图片url
     * @param images       imageWatcher的辅助变量
     * @param urlList      imageWatcher的辅助变量
     * @param ifOnlyOne    是否是单张图
     */
    public void addImageIntoLayout(Context mContext, int currentIndex, LinearLayout layout, String url, final List<ImageView> images, final List<String> urlList, boolean ifOnlyOne) {
        int eachWidth = 92; //多张图时的每张图宽度
        deal(mContext, eachWidth, currentIndex, layout, url, images, urlList, ifOnlyOne);
    }


    private void deal(Context mContext, int eachWidth, int currentIndex, LinearLayout layout, String url, final List<ImageView> images, final List<String> urlList, boolean ifOnlyOne) {
        final ImageView iv = new ImageView(mContext);
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //iv.setAdjustViewBounds(true);
        LinearLayout.LayoutParams layoutParams;
        int boundaryValue = dp2px(mContext, 180);
        if (ifOnlyOne) {//如果仅仅是一张图的情况，就等比例缩小
            if (ifParseSizeCorrect) {// 如果解析正常，就按照正常流程走
                if (widthOfSingleImg > boundaryValue || heightOfSingleImg > boundaryValue) {// 如果存在宽或者高，超出临界值的情况
                    //就设定边界，让图片在最大范围内缩小
                    layoutParams = initLayoutParam(boundaryValue);
                } else {//如果到了这里，说明宽高都小于临界值
                    if (widthOfSingleImg * 2 > boundaryValue || widthOfSingleImg * 2 > boundaryValue) {// 那么，判定宽高的两倍有没有达到180，如果达到了，那么久放大显示
                        layoutParams = initLayoutParam(boundaryValue);
                    } else {// 宽和高都小于临界值的一半，那么，原图显示吧
                        layoutParams = new LinearLayout.LayoutParams(widthOfSingleImg, heightOfSingleImg);
                    }
                }

            } else {//如果出现异常（可能是旧版本的图，上传的时候没有传size参数），就让他自适应吧
                layoutParams = new LinearLayout.LayoutParams(boundaryValue, boundaryValue);
            }
            iv.setMaxWidth(boundaryValue);
            iv.setMaxHeight(boundaryValue);
        } else//多图情况，就只用原图的中间区域来填充
        {
            layoutParams = new LinearLayout.LayoutParams(dp2px(mContext, eachWidth), dp2px(mContext, eachWidth));
            iv.setMaxWidth(dp2px(mContext, eachWidth));
            iv.setMaxHeight(dp2px(mContext, eachWidth));

            if (currentIndex != urlList.size() - 1)
                layoutParams.rightMargin = dp2px(mContext, rightMargin);
        }

        images.add(iv);

        urlList.add(url);
        layout.addView(iv, layoutParams);

        if (url != null && url.length() > 0) {
            Glide.with(mContext).load(url).placeholder(R.mipmap.a_forum_nopic1).error(R.mipmap.a_forum_nopic1).into(iv);
        } else {
            iv.setVisibility(View.GONE);
        }

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                watcher.show(iv, images, urlList);
            }
        });
    }


    private LinearLayout.LayoutParams initLayoutParam(int boundaryValue) {
        LinearLayout.LayoutParams layoutParams;
        if (widthOfSingleImg > heightOfSingleImg) {//宽大于高
            float x = (float) boundaryValue / widthOfSingleImg;// 计算等比例高度
            int targetH = (int) (heightOfSingleImg * x);
            layoutParams = new LinearLayout.LayoutParams(boundaryValue, targetH);
        } else {//高大于宽
            float x = (float) boundaryValue / heightOfSingleImg;
            int targetW = (int) (widthOfSingleImg * x);
            layoutParams = new LinearLayout.LayoutParams(targetW, boundaryValue);
        }
        return layoutParams;
    }
}
